import { getAllCars } from '@/api/car'
import { simpleOrderList } from '@/api/order'
const updateOrderNum = (state, v, subtract) => {
  if (v.status === 1) {
    switch (v.orderType) {
      case 1:
        state.order.temporarys += subtract ? -1 : 1
        break
      case 2:
        state.order.reservations += subtract ? -1 : 1
        break
      default:
        state.order.helps += subtract ? -1 : 1
        break
    }
  }
  onUpdateOrderStatus(state, v)
}
const onUpdateOrderStatus = (state, v) => {
  switch (v.status) {
    case 2:
      state.order.ongoing += 1
      break
  }
}
const app = {
  state: {
    order: {
      datas: [],
      temporarys: 0,
      reservations: 0,
      helps: 0,
      ongoing: 0
    },
    car: {
      datas: []
    },
    /**
     * 调派中心状态
     */
    controlStatus: 0
  },
  mutations: {

    REMOVE_ORDER: (state, order) => {
      state.order.datas = state.order.datas.map(v => {
        if (v.orderId !== order.orderId) {
          return v
        } else {
          updateOrderNum(state, v, true)
        }
      }, state.order.datas)
    },
    ADD_ORDER: (state, orders) => {
      state.order.datas = state.order.datas.concat(orders)
      orders.forEach(v => {
        updateOrderNum(state, v, false)
      })
    },
    CHANGE_ORDER_STATUS: (state, orderNo, status) => {
      state.order.datas = state.order.datas.map(v => {
        if (v.orderId === orderNo) {
          v.status = status
          onUpdateOrderStatus(state, v)
        }
        return v
      }, state.order.datas)
    },
    ADD_CAR: (state, cars) => {
      state.car.datas = state.car.datas.concat(cars)
    },
    CHANGE_CONTROL_STATUS: (state, status) => {
      state.controlStatus = status
    }
  },
  actions: {
    addOrder: ({ commit }, order) => {
      commit('ADD_ORDER', [order])
    },
    initSysteData: ({ commit }) => {
      getAllCars().then(res => {
        commit('ADD_CAR', res.records)
      })
      simpleOrderList().then(res => {
        commit('ADD_ORDER', res)
      })
    },
    removeOrder: ({ commit }, order) => {
      commit('REMOVE_ORDER', order)
    },
    changeOrderStatus: ({ commit }, orderId, status) => {
      commit('CHANGE_ORDER_STATUS', orderId, status)
    },
    changeControlStatus: ({ commit }, status) => {
      commit('CHANGE_CONTROL_STATUS', status)
    }
  }
}

export default app
